import React, { Component, useRef, useState } from 'react';
import styles from './UserManagement.less';
import { Card, Button, Table, Select, Badge, Space, Popconfirm, Modal, Form, Input, notification, Icon, Checkbox, Row } from 'antd'
import {
  TeamOutlined,
  EditOutlined,
  StopOutlined,
  CheckCircleOutlined,
  LockOutlined,
  UserOutlined,
  SearchOutlined
} from '@ant-design/icons';
import axios from 'axios';
import moment from 'moment'
import { ConfigProvider } from 'antd';

import zh_CN from 'antd/es/locale/zh_CN';
// import { v4 as uuidv4 } from 'uuid';


class UserManagement extends Component {

  constructor() {
    super();
    this.searchInput = React.createRef();
    this.state = {
      dataSource: [],
      activeTabKey: '1',
      tabList: [],
      staffType: "",// 员工类型
      loading: false,
      total: 0,
      pageNum: 1,
      pageSize: 20,
      selectedRowKeys: [],
      searchedColumn: '',
      searchText: '',
      sysUserId: '',
      chooseItem: [],
      remark: '',
      dutyList: [{ staffJobId: 'zw001', staffJobName: '招聘专员' }, { staffJobId: 'zw002', staffJobName: '运营专员' }], // 职务列表,
      isModalOpen: false,  //编辑职务弹窗控制
      freezeOpen: false,  //冻结账户弹窗控制,
      countOpen: false,   //设置账户弹窗控制
      newPwsOpen: false,  //编辑密码的弹窗控制
      staffOpen: false, //冻结/恢复员工弹窗控制
      modalType: '',
      returnOpen: false, //恢复账户弹窗控制
      staffJobName: '',
      FormData: {}
    }
  }

  componentDidMount() {
    this.getUserList()
    this.tabPermission()
    const {
      searchedColumn,
      searchText
    } = this.state;
  }

  //获取列表数据
  getUserList = () => {
    axios.get('/api/UserManagement/getUserList').then((res) => {
      if (res.status == 200) {
        console.log(res.data)
        this.setState({
          dataSource: res.data.data.data ? res.data.data.data : [],
          loading: false,
        })
      }
    })
  }

  // tab权限
  tabPermission = () => {
    let list = [
      {
        key: '1',
        tab: '用户列表',
      }
    ];
    this.setState({
      tabList: list
    });
    this.onTabChange(list[0].key);
  };

  // tab切换
  onTabChange = key => {
    console.log(key);
    this.setState({ activeTabKey: key, pageNum: 1, pageSize: 10 });
    // key === '1' && this.getTestList();
  };

  // 页码或分页变化
  pageChange = (pageNum, pageSize) => {
    this.setState({ pageNum, pageSize, loading: true })
  }

  //选中行变化事件
  onSelectChange = (newSelectedRowKeys, selectedRows) => {
    console.log('selectedRows: ', selectedRows);
    this.setState({
      selectedRowKeys: newSelectedRowKeys,
      chooseItem: selectedRows,
      remark: ''
    });
  }

  // * 表格总变化回调
  //    */
  onApprovalTableChange = (pagination, filters, sorter, extra) => {
    console.log('params', pagination, filters, sorter, extra);
    //对最后登陆时间进行排序
    if (sorter.field === 'createTime') {
      const { dataSource } = this.state;
      const newDataSource = [...dataSource].sort((a, b) => {
        const dateA = a.createTime ? new Date(a.createTime) : new Date(0);
        const dateB = b.createTime ? new Date(b.createTime) : new Date(0);
        return sorter.order === 'ascend' ? dateA - dateB : dateB - dateA;
      });
      this.setState({ dataSource: newDataSource });
    }
    this.setState({ loading: false });

  };

  //点击搜索
  handleSearch = (selectedKeys, confirm, dataIndex) => {
    // const key = dataIndex;
    const params = {
      [dataIndex]: selectedKeys[0],
    }
    axios.get('/api/UserManagement/getUserList', { params }).then((res) => {
      if (res.status == 200) {
        console.log(res.data)
        this.setState({ dataSource: res.data.data.data ? res.data.data.data : [], loading: false })
      }
    })
    console.log(params);
  };

  //点击重置
  handleReset = selectedKeys => {
    selectedKeys[0] = '';
    axios.get('/api/UserManagement/getUserList').then((res) => {
      if (res.status == 200) {
        console.log(res.data)
        this.setState({ dataSource: res.data.data.data ? res.data.data.data : [], loading: false })
      }
    })
  };


  //模糊搜索组件
  getColumnSearchProps = (dataIndex, title) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        style={{
          padding: 8,
        }}
        onKeyDown={(e) => e.stopPropagation()}
      >
        <Input
          ref={this.searchInput}
          placeholder={`请输入${title}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: 'block',
          }}
        />
        <Space>
          <Button
            onClick={() => this.handleReset(selectedKeys)}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
          <Button
            onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            type="primary"
            style={{
              width: 90,
            }}
          >
            搜索
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? '#1677ff' : undefined,
        }}
      />
    ),
  });

  //编辑职务
  handleAddMember = () => {
    const { chooseItem } = this.state;
    if (Object.keys(chooseItem).length === 0) {
      notification.warning({
        message: '请选择用户'
      })
    } else {
      this.setState({ isModalOpen: true });
    }

  }

  //职务变化时触发
  staffJobNameChange = (value) => {
    console.log(value)
    const job = this.state.dutyList.find(item => item.staffJobId === value);
    console.log(job.staffJobName)

    // this.setState({ staffJobName: job.staffJobName });
    const updatedChooseItem = this.state.chooseItem.map(item => ({
      ...item,
      staffJobName: job.staffJobName, // 修改staffJobName的值  
    }));

    this.setState({ chooseItem: updatedChooseItem });
  }

  handleOk = () => {
    const { chooseItem, dataSource } = this.state;
    if (!Array.isArray(chooseItem) || !Array.isArray(dataSource)) {
      console.error("chooseItem 或 datasource 不是数组");
    } else {
      axios.post('/api/UserManagement/addUser', chooseItem).then((res) => {
        if (res.status == 200) {
          console.log(res.data)
          this.setState({
            dataSource: res.data.data ? res.data.data : [],
            loading: false,
            isModalOpen: false,
            chooseItem: [],
            selectedRowKeys: [],
            remark: ''
          })
        }
      })

    }

  }

  // onFinish = (values) => {
  //   console.log('Success:', values);
  // };
  // onFinishFailed = (errorInfo) => {
  //   console.log('Failed:', errorInfo);
  // };

  onClose = () => {
    this.setState({ isModalOpen: false, chooseItem: [], selectedRowKeys: [], remark: '' });
  }

  // //冻结员工/恢复员工/重置密码
  handleBatchVisible(value) {
    const { chooseItem } = this.state;
    if (Object.keys(chooseItem).length === 0) {
      notification.warning({
        message: '请选择用户'
      })
    } else {
      if (value == '0') {
        chooseItem.forEach(item => {
          if (item.isForbidden === "true") {
            notification.error({
              message: '当前为冻结状态，无需进行冻结'
            })
          } else {
            this.setState({ staffOpen: true, modalType: value });
          }
        })

      } else if (value == '1') {
        chooseItem.forEach(item => {
          if (item.isForbidden === "") {
            notification.error({
              message: '当前为正常状态，无需进行恢复'
            })
          } else {
            this.setState({ staffOpen: true, modalType: value });
          }
        })

      } else if (value == '2') {
        //编辑密码
        this.setState({ newPwsOpen: true });
      }
    }


  }

  //编辑密码
  resetNewPsw = () => {
    const { FormData } = this.state;
    console.log(FormData)
    this.setState({ newPwsOpen: false });

  }


  //关闭弹窗
  close = () => {
    this.setState({ countOpen: false });  //设置账户时关闭
    this.setState({ freezeOpen: false });  //冻结账户时关闭
    this.setState({ newPwsOpen: false });  //编辑密码时关闭
    this.setState({ returnOpen: false });   //恢复账户时关闭
  }


  //设置/冻结/恢复账户
  menuClick = (value, text, record) => {
    console.log(record)
    const tempItem = []
    tempItem.push(record)
    this.setState({ chooseItem: tempItem });
    if (value == '0') {
      console.log(record)
      this.setState({ FormData: record, countOpen: true, modalType: value });
    } else if (value == '3') {

      this.setState({ freezeOpen: true, modalType: value });
    } else if (value == '4') {

      this.setState({ returnOpen: true, modalType: value });
    }

  }


  //冻结账户
  setCountFro = () => {
    const { chooseItem, dataSource } = this.state;
    const newisForbidden = "true"
    const updatedChooseItem = chooseItem.map(item => ({
      ...item,
      isForbidden: newisForbidden, // 修改isForbidden的值  
    }));
    this.setState({ chooseItem: updatedChooseItem }, () => {
      console.log(this.state.chooseItem)
      // 在这里使用更新后的 chooseItem  
      if (!Array.isArray(this.state.chooseItem) || !Array.isArray(dataSource)) {
        console.error("chooseItem 或 datasource 不是数组");
      } else {
        axios.post('/api/UserManagement/addUser', this.state.chooseItem).then((res) => {
          if (res.status == 200) {
            console.log(res.data)
            this.setState({
              dataSource: res.data.data ? res.data.data : [],
              loading: false,
              freezeOpen: false,
              chooseItem: [],
              selectedRowKeys: [],
            })
          }
        })
      }
    });
  }

  //设置账户
  countSet = (value, text, record) => {
    console.log(record)
    console.log(this.state.FormData)
    this.setState({ countOpen: false });
  }

  //冻结员工/恢复员工/重置密码
  handleOperate = () => {
    const { chooseItem, dataSource, modalType } = this.state;
    if (modalType == '0') {
      const newisForbidden = "true"
      const updatedChooseItem = chooseItem.map(item => ({
        ...item,
        isForbidden: newisForbidden, // 修改isForbidden的值  
      }));
      this.setState({ chooseItem: updatedChooseItem }, () => {
        console.log(this.state.chooseItem)
        // 在这里使用更新后的 chooseItem  
        if (!Array.isArray(this.state.chooseItem) || !Array.isArray(dataSource)) {
          console.error("chooseItem 或 datasource 不是数组");
        } else {
          axios.post('/api/UserManagement/addUser', this.state.chooseItem).then((res) => {
            if (res.status == 200) {
              console.log(res.data)
              this.setState({
                dataSource: res.data.data ? res.data.data : [],
                loading: false,
                staffOpen: false,
                chooseItem: [],
                selectedRowKeys: [],
              })
            }
          })
        }
      });

    } else if (modalType == '1') {
      const newisForbidden = ""
      const updatedChooseItem = chooseItem.map(item => ({
        ...item,
        isForbidden: newisForbidden, // 修改isForbidden的值  
      }));
      this.setState({ chooseItem: updatedChooseItem }, () => {
        console.log(chooseItem)
        // 在这里使用更新后的 chooseItem  
        if (!Array.isArray(this.state.chooseItem) || !Array.isArray(dataSource)) {
          console.error("chooseItem 或 datasource 不是数组");
        } else {
          axios.post('/api/UserManagement/addUser', this.state.chooseItem).then((res) => {
            if (res.status == 200) {
              console.log(res.data)
              this.setState({
                dataSource: res.data.data ? res.data.data : [],
                loading: false,
                staffOpen: false,
                chooseItem: [],
                selectedRowKeys: [],
              })
            }
          })
        }
      });
    }



  }

  staffClose = () => {
    this.setState({ staffOpen: false });
  }

  //恢复账户
  returnCountFro = () => {
    const { chooseItem, dataSource } = this.state;
    const newisForbidden = ""
    const updatedChooseItem = chooseItem.map(item => ({
      ...item,
      isForbidden: newisForbidden, // 修改isForbidden的值  
    }));
    this.setState({ chooseItem: updatedChooseItem }, () => {
      console.log(this.state.chooseItem)
      // 在这里使用更新后的 chooseItem  
      if (!Array.isArray(this.state.chooseItem) || !Array.isArray(dataSource)) {
        console.error("chooseItem 或 datasource 不是数组");
      } else {
        axios.post('/api/UserManagement/addUser', this.state.chooseItem).then((res) => {
          if (res.status == 200) {
            console.log(res.data)
            this.setState({
              dataSource: res.data.data ? res.data.data : [],
              loading: false,
              returnOpen: false,
              chooseItem: [],
              selectedRowKeys: [],
            })
          }
        })
      }
    });
  }



  render() {
    const {
      dataSource,
      activeTabKey,
      tabList,
      staffType,
      loading,
      total,
      pageNum,
      pageSize,
      selectedRowKeys,
      searchedColumn,
      searchText,
      sysUserId,
      chooseItem,
      remark,
      dutyList,
      isModalOpen,
      freezeOpen,
      countOpen,
      newPwsOpen,
      staffOpen,
      modalType,
      returnOpen,
      staffJobName,
      FormData
    } = this.state;

    const pagination = {
      total,
      showSizeChanger: true,
      pageSize: 10,
      current: pageNum,
      showTotal: (total) => `共 ${total} 条`,
      pageSizeOptions: ['10', '20', '50', '100', '200', '500'],
      onChange: this.pageChange,
      onShowSizeChange: this.pageChange
    }


    const staffTypeFilterItem = [
      {
        text: '本部',
        value: '本部',
      },
      {
        text: '项目',
        value: '项目',
      },
      {
        text: '顾问',
        value: '顾问',
      },
      {
        text: '实习',
        value: '实习',
      }, {
        text: '退休返聘',
        value: '退休返聘',
      }
    ]
    const isForbiddenFilterItem = [{
      text: '正常',
      value: '',
    },
    {
      text: '冻结',
      value: 'true',
    },]

    const rowSelection = {
      selectedRowKeys,
      type: 'checkbox',
      onChange: this.onSelectChange,
    }


    // 列表表头
    const columns = [
      {
        title: '头像',
        dataIndex: 'sysUserHead',
        render: (text, record, index) => <div>{!text ? <Space><UserOutlined /></Space> : <Space><UserOutlined /></Space>}</div>
      },
      {
        title: '姓名',
        dataIndex: 'staffName',
        ...this.getColumnSearchProps('staffName', '姓名')
      },
      {
        title: '部门',
        dataIndex: 'deptName',
        ...this.getColumnSearchProps('deptName', '部门')
      },
      {
        title: '员工类别',
        dataIndex: 'staffType',
        filters: staffTypeFilterItem,
        onFilter: (value, record) => record.staffType.indexOf(value) === 0,
      },
      {
        title: '职务/技能',
        dataIndex: 'staffJobName',
        ...this.getColumnSearchProps('staffJobName', '职务/技能')
      },
      {
        title: '手机',
        dataIndex: 'phoneNum',
        ...this.getColumnSearchProps('phoneNum', '手机')
      },
      {
        title: '账号状态',
        dataIndex: 'isForbidden',
        filters: isForbiddenFilterItem,
        onFilter: (value, record) => record.isForbidden.indexOf(value) === 0,
        render: (text, record, index) => <Badge status={!text ? 'success' : 'warning'} text={!text ? '正常' : '冻结'} />,
      },
      {
        title: '最后登录',
        dataIndex: 'createTime',
        sorter: true,
        render: (text, record, index) => <span>{!text ? '-' : moment(text).format('YYYY-MM-DD')}</span>
      },
      {
        title: '操作',
        dataIndex: 'staffId',
        align: 'center',
        render: (text, record, index) => <div>
          {<Button type="link" onClick={() => this.menuClick('0', text, record)}>设置</Button>}
          {<Button type="link" onClick={() => this.menuClick(!record.isForbidden ? '3' : '4', text, record)}>{!record.isForbidden ? '冻结' : '恢复'}</Button>}
        </div>
      }
    ]

    return (
      <div>
        <Card
          bordered={false}
          className={styles.mb24}
          activeTabKey={activeTabKey}
          onTabChange={(key) => this.onTabChange(key)}
          tabList={tabList}
        >
          {activeTabKey === '1' && (
            <div style={{ position: 'absolute', top: '12px', right: '20px' }}>
              {<Button className={styles.marginR16} icon={<EditOutlined />} onClick={this.handleAddMember}  >
                编辑职务
              </Button>}
              {<Button className={styles.marginR16} icon={<StopOutlined />} onClick={() => this.handleBatchVisible(0)}>
                冻结员工
              </Button>}
              {<Button className={styles.marginR16} icon={<CheckCircleOutlined />} onClick={() => this.handleBatchVisible(1)}>
                恢复员工
              </Button>}
              {<Button icon={<LockOutlined />} onClick={() => this.handleBatchVisible(2)}>
                重置密码
              </Button>}
            </div>
          )}
          {activeTabKey === '1' &&
            <ConfigProvider locale={zh_CN}>
              <Table
                rowKey="sysUserId"
                loading={loading}
                locale=""
                dataSource={dataSource}
                columns={columns}
                pagination={pagination}
                rowSelection={rowSelection}
                scroll={{ x: 'max-content' }}
                onChange={this.onApprovalTableChange}
              // getPopupContainer={() => document.body}
              />
            </ConfigProvider>
          }
        </Card>
        <Modal
          title="设置账户"
          // visible={countSetVis}
          onOk={this.countSet}
          onCancel={this.close}
          centered
          destroyOnClose={true}
          open={countOpen}
          
        >
          {/* <Form> */}
          <Form.Item name="userCode" label="原账户" layout="vertical">
            {(
              <Input defaultValue={FormData.userCode} disabled />
            )}
          </Form.Item>
          <Form.Item name="newuserCode" label="新账户" layout="vertical" rules={
            [{ required: true, message: '请输入新账户', }]}>
            {(
              <Input defaultValue={FormData.newuserCode} value={FormData.newuserCode} placeholder="新账户" />
            )}
          </Form.Item>
          {/* </Form> */}
        </Modal>

        <Modal
          title="重置密码"
          // visible={pswVis}
          onOk={this.resetNewPsw}
          onCancel={this.close}
          open={newPwsOpen}
          destroyOnClose={true}
        >
          <Form.Item name="newPwd" label="新密码" layout="vertical" rules={
            [{ required: true, message: '请填写新密码', },
            { pattern: /^[0-9a-zA-Z !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]{6,16}$/, message: '请设置正确格式密码' }]}>
            {(
              <Input.Password value={FormData.newPwd} placeholder="新的登录密码" />
            )}
          </Form.Item>
          <Form.Item name="againPwd" label="确认密码" layout="vertical" rules={
            [{ required: true, message: '请填写确认密码', }]}>
            {(
              <Input.Password value={FormData.againPwd} placeholder="确认新密码" />
            )}
          </Form.Item>
        </Modal>
        <Modal
          title="冻结账户"
          // visible={countFrozenVis}
          onOk={this.setCountFro}
          onCancel={this.close}
          centered
          open={freezeOpen}
        >
          <Form.Item name="reason" label="冻结原因" layout="vertical" rules={
            [{ required: true, message: '请填写冻结原因', }, { max: 200, message: '冻结原因内容超出限定范围（200字）' }]}>
            {(
              <Input.TextArea rows={3} placeholder="请填写冻结原因" />
            )}
          </Form.Item>
        </Modal>

        <Modal
          title="恢复账户"
          onOk={this.returnCountFro}
          onCancel={this.close}
          centered
          open={returnOpen}
        >
          <Form.Item name="reason" label="恢复原因" layout="vertical" rules={
            [{ required: true, message: '请填写恢复原因', }, { max: 200, message: '恢复原因内容超出限定范围（200字）' }]}>
            {(
              <Input.TextArea rows={3} placeholder="请填写恢复原因" />
            )}
          </Form.Item>
        </Modal>

        <Modal
          title="编辑职务"
          onOk={this.handleOk}
          onCancel={this.onClose}
          centered
          okText="保存"
          destroyOnClose={true}
          open={isModalOpen}
          // footer={null}
        >
          {/* <Form onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}> */}
            <Form.Item name="staffName" label="已选员工" layout="vertical" rules={
              [{ required: true, message: '请选择人员', },]}>
              {(
                <Select
                  mode="multiple"
                  placeholder="请选择人员"
                  style={{ width: '100%' }}
                  defaultValue={chooseItem.map(item => item.staffName)}
                >
                  {chooseItem.map(item => <Option key={item.sysUserId} value={item.sysUserId}>{item.staffName}</Option>)}
                </Select>
              )}
            </Form.Item>
            <Form.Item
              rules={
                [{ required: true, message: '请选择职务', },]} name="staffJobName" label="编辑职务" layout="vertical" extra="如果该员工已被分配其它职务，添加后员工将被编辑职务">
              {(
                <Select
                  placeholder="请选择职务"
                  style={{ width: '100%' }}
                  defaultValue={chooseItem.map(item => item.staffJobName)}
                  value={staffJobName}
                  onChange={this.staffJobNameChange}
                >
                  {dutyList.map(item => <Option key={item.staffJobId} value={item.staffJobId}>{item.staffJobName}</Option>)}
                </Select>
              )}
            </Form.Item>
            <Form.Item name="remark" label="原因备注" layout="vertical" rules={
              [{ required: true, message: '请输入原因备注' },
              { max: 200, message: '原因备注内容超出限定范围（200字）' }]} >
              {(<Input.TextArea
                placeholder="请输入原因备注"
                rows={4}
                value={remark}
              />)}
            </Form.Item>
            {/* <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button htmlType="button" onClick={this.onClose}>取消</Button>
              <Button type="primary" htmlType="submit">保存</Button>
            </Form.Item>
          </Form> */}
        </Modal>

        <Modal
          title={!modalType ? '冻结员工' : (modalType === 1 ? '恢复员工' : '重置密码')}
          onOk={this.handleOperate}
          onCancel={this.staffClose}
          okText="保存"
          centered
          destroyOnClose={true}
          open={staffOpen}
        // bodyStyle={{ overflowY: "initial" }}
        >
          <Form.Item name="staffName" label="已选员工" layout="vertical" rules={
            [{ required: true, message: '请选择人员', },]}>
            {(
              <Select
                mode="multiple"
                placeholder="请选择人员"
                style={{ width: '100%' }}
                defaultValue={chooseItem.map(item => item.staffName)}
              >
                {chooseItem.map(item => <Option key={item.sysUserId} value={item.sysUserId}>{item.staffName}</Option>)}
              </Select>
            )}
          </Form.Item>
          <Form.Item name="reason" label="原因备注" layout="vertical" rules={
            [{ required: true, message: '请输入原因备注' },
            { max: 200, message: '原因备注内容超出限定范围（200字）' }]}>
            {(<Input.TextArea
              placeholder="请输入原因备注"
              rows={4}
            />)}
          </Form.Item>
        </Modal>
      </div>
    );
  }
}
export default UserManagement;